package com.medistat.dialog.services;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.medistat.dialog.Schedule;
import com.medistat.dialog.ScheduleCell;
import com.medistat.model.Doctor;
import com.medistat.model.Work;
import com.medistat.model.enums.Days;
import com.medistat.model.enums.TypeOfWork;
import com.medistat.util.DateUtils;

@Service("loadScheduleStrategy")
public class LoadScheduleStrategy extends ScheduleCreator {
	
	Map<String, Work> worksCache;

	@Override
	protected void secondPass(List<Schedule> schedules) throws Exception {
		//if last day in month is sunday we should leave cells active
		Schedule lastScheduleInMonth = schedules.get(schedules.size()-1);
		lastDayInMonthDutyAssignement(lastScheduleInMonth);
	}
	
	private void lastDayInMonthDutyAssignement(Schedule schedule) {
		
		Calendar firstDateInLastScheduleForMonth = schedule.getScheduleSelections().get(0).getScheduleCells().get(0).getDate();
		Calendar lastDate = DateUtils.getMaxDate(firstDateInLastScheduleForMonth);
		Days lastDay = DateUtils.getDayFrom(lastDate);
		
		//if last day is friday or sunday - last day should not be extra handled.
		if(DateUtils.isFriday(lastDay) || DateUtils.isSunday(lastDay)) {
			return;
		}

		Calendar tommorow = DateUtils.addDate(lastDate, 1);
		List<ScheduleCell> tommorowScheduleCells = schedule.getCellsForDay(DateUtils.getDayFrom(tommorow));
		
		//saturday  - mark sunday cells as active
		if(DateUtils.isSaturday(lastDay)) {
			for(ScheduleCell scheduleCell : tommorowScheduleCells) {
				scheduleCell.setActive(true);
			}
		} 		
	}

	@Override
	protected Doctor findAvailableDoctor(Calendar date, TypeOfWork typeOfWork, ScheduleCell scheduleCell) throws Exception {
		String key = composeKey(date, typeOfWork);
		Work work = worksCache.get(key);
		if(work==null) {
			return null;
		}
		//comment out because of functionality of later editing loaded schedule and also excel file but not values in DB.
		//scheduleCell.setActive(false);
		return work.getDoctor();
	}
	
	@Override
	protected void beforeCreation(Integer year, Calendar date) {
		worksCache = new HashMap<String, Work>();
		Calendar dateTo = DateUtils.getMaxDate(date);
		List<Work> works = persistanceService.findWorksBetween(date, dateTo);
		for(Work work : works) {
			String key = composeKey(work.getDate(), work.getTypeOfWork());
			worksCache.put(key, work);
		}
	}

	private String composeKey(Calendar date, TypeOfWork typeOfWork) {		
		return date.get(Calendar.YEAR) + "_" + date.get(Calendar.MONTH) + "_" + date.get(Calendar.DATE) + "_" + typeOfWork;
	}

	@Override
	protected void afterCreation() {
		worksCache = null;
	}


}
